// +build !fake
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"iot-base/common/cache"
	cpt "iot-base/common/cache/picktemplate"
	"iot-base/common/dbconn"
	"iot-base/common/eventtype"
	"iot-base/common/notify"
	"net"
	"sort"
	"strconv"
	"strings"
	"time"

<<<<<<< HEAD
	lcache "github.com/patrickmn/go-cache"

=======
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
	"gorm.io/gorm"

	"iot-base/common/logger"
	rc "iot-base/common/redis"

	"github.com/google/uuid"
)

type AlarmEvent struct {
	REQ string
	Ok  []AlarmDev
}

type AlarmDev struct {
	UID string
	Eve []string
}

type ErrLog struct {
	Id   string `gorm:"primarykey"`
	Sbbh string
	Gzxx string
	Rzsj time.Time
	By1  string
	By2  string
	By3  string
	By4  string
	By5  string
}

func (pErrLog *ErrLog) TableName() string {
	return "sbrzb"
}

var lc *lcache.Cache

func init() {
	dbconn.DBConnection.AutoMigrate(&ErrLog{})
	lc = lcache.New(60*time.Minute, 60*time.Minute)
}

var AlarmList = map[string]string{
	"0":  "powerOffline",
	"1":  "powerOffline",
	"2":  "over current",
	"3":  "leak",
	"4":  "power unstable",
	"5":  "offline",
	"6":  "connect close",
	"7":  "board offline",
	"8":  "board voltage error",
	"9":  "outlet current high",
	"10": "outlet delay error",
	"11": "220V error",
	"12": "12V error",
	"13": "24V error",
	"14": "SMbus error",
	"15": "temperature error",
	"16": "humity error",
	"17": "ACC tilt",
	"18": "box shock",
	"19": "CameraOffline",
	"20": "Low speed",
	"21": "Inwater",
	"22": "Lightning protection failure",
	"23": "Smoke generation",
	"24": "Unauthorized",
	"25": "unlocked",
}
var AlarmExplainList = map[string]string{
	"0":  "市电故障",
	"1":  "DC12V断电",
	"2":  "过流",
	"3":  "设备漏电",
	"4":  "电源不稳",
	"5":  "网络故障",
	"6":  "重合闸断开",
	"7":  "单板掉线",
	"8":  "单板电压故障",
	"9":  "输出电流过高",
	"10": "继电器出错",
	"11": "220V出错",
	"12": "12V过欠压",
	"13": "24V出错",
	"14": "SMbus 错误",
	"15": "温度告警",
	"16": "湿度告警",
	"17": "机箱倾斜",
	"18": "机箱震动",
	"19": "摄像机断线",
	"20": "转速过低",
	"21": "水浸",
	"22": "防雷设备失效",
	"23": "烟感报警",
	"24": "未授权",
	"25": "未锁门",
}

const interfaceFHKey = "fh.interface.alarm"

func saveAlarmDict(eve []string, id string, ip string) {
	var state string
	//var current = 0
	var hasPowerOffline = false
	var hasOffline = false
	elen := len(eve)
	if elen == 0 {
		state = "无告警"
	} else {
		for _, e := range eve {
			if e == "0" || e == "1" {
				hasPowerOffline = true
			}
			if e == "5" {
				hasOffline = true
			}
		}
		if hasPowerOffline && hasOffline {
<<<<<<< HEAD
			state = "市电掉电"
		} else if hasOffline {
			state = "网络故障"
		} else {
			var aid string

			for _, e := range eve {
				if e == "0" || e == "1" || e == "2" || e == "3" || e == "4" {
					continue
				}
=======
			state = AlarmExplainList["0"]
		} else {
			var aid string
			for _, e := range eve {

>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
				name, ok := AlarmExplainList[e]
				if !ok {
					continue
				}
<<<<<<< HEAD
=======

>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
				aid = AlarmList[e]

				if aid == "" {
					continue
				}
				isEnabled := cpt.IsAlarmEnable(id, aid)
				if !isEnabled {
					continue
				}
				if state == "" {
					state = name
				} else {
					state = state + "," + name
				}
				//current++

			}

		}

	}
	if state == "" {
		state = "无告警"
	}

<<<<<<< HEAD
	var log ErrLog
	id1, _ := uuid.NewUUID()
	log.Id = id1.String()
	log.Sbbh = ip
	log.Gzxx = state
	log.Rzsj = time.Now()
	oldState, _ := lc.Get(id)
	if oldState != state {
		dbconn.DBConnection.Create(&log)
		lc.Set(id, state, lcache.NoExpiration)
		logger.SLog.Info("to fenghuo:", state, " ip:", ip, " ave:", eve)
	} else {
		logger.SLog.Warn("to fenghuo giveup:", state, " ip:", ip, " ave:", eve)
=======
	if state != "" {
		var log ErrLog
		id1, _ := uuid.NewUUID()
		log.Id = id1.String()
		log.Sbbh = ip
		log.Gzxx = state
		log.Rzsj = time.Now()
		dbconn.DBConnection.Create(&log)
		logger.SLog.Warn("to fenghuo:", state, " id:", ip)
	} else {
		logger.SLog.Warn("give up rz state", eve)
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
	}

}

func saveAlarm(eve []string, id string, ip string) {

<<<<<<< HEAD
=======
	if len(eve) == 1 && eve[0] == "5" {
		return
	}
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
	saveAlarmDict(eve, id, ip)
}

var chanForID = make(chan string)

type alarmInfo struct {
	pAlarm *eventtype.Alarm
	count  int
	ip     string
}

func ReportAlarm() {
	//fmt.Println("---------------get alarms------------------")
	//ctx := redis.GetRCContext()
	//rc := redis.GetRCClient()

	//var lastSaved = time.Now().Unix()
	alarmLocalMap, _ := rc.HGetAll(interfaceFHKey).Result()
	alarmDelay := make(map[string]*alarmInfo)

	count := 0
	alarmconn, _ := net.DialTimeout("tcp", "127.0.0.1:37125", 3*time.Second)
	mapIP := make(map[string]string)
	//alarmLocalMap := make(map[string]string)
	devids := make([]string, 0, 20)
	t := time.NewTicker(2 * time.Second)
	for {
		select {
		case <-t.C:
			count++
			getAlarms(alarmLocalMap, devids, mapIP, count, alarmconn, alarmDelay)
			now := time.Now()
			for k, v := range alarmDelay {
				v.count--
				if v.count <= 0 {
					logger.SLog.Info("send alarm---------", v.pAlarm)
					v.pAlarm.Time = now.Unix()
					//notify.RawAlarm(v.pAlarm)
					pAlarms := []*eventtype.Alarm{v.pAlarm}
					ids := []string{k}
					notify.ReportAllAlarms(pAlarms, ids)
					saveAlarmDict([]string{"5"}, k, v.ip)
					delete(alarmDelay, k)
				}
			}
		case id := <-chanForID:
			if id != "" {
				delete(alarmLocalMap, id)
				lc.Delete(id)
			}

		}

	}
}

func getAlarms(alarmLocalMap map[string]string, devids []string, mapIP map[string]string,
	count int, alarmconn net.Conn, alarmDelay map[string]*alarmInfo) {

	timeout := 2
	var err error
	devids = devids[:0]
	time.Sleep(time.Duration(timeout) * time.Second)
	if alarmconn == nil {
		logger.SLog.Error("connet dev error")
		alarmconn, err = net.DialTimeout("tcp", "127.0.0.1:37125", 3*time.Second)
		if alarmconn == nil {
			logger.SLog.Error("connet dev retry error", err)
			time.Sleep(3 * time.Second)
			return
		}
	}

	if count > 10 && count%(30*20) == 0 { //20分钟向redis同步一次
		tempMap := make(map[string]interface{})
		for k, v := range alarmLocalMap {
			tempMap[k] = v
		}
		rc.HSetMap(interfaceFHKey, tempMap)
	}

	alarmconn.Write([]byte(`{"REQ":"GetEvent","Dev":[{"UID":"All"}]}\r\n`))
	//fmt.Println(`{"REQ":"GetEvent","Dev":[{"UID":"All"}]}`)
	rd, err := ReadDtEx(alarmconn)
	fmt.Println("----------------read alarm----------error---", err)
	if err == io.EOF {
		alarmconn = nil
		return
	}
	//fmt.Println("get from devp------------", string(rd))

	//fmt.Println("alarm return:", string(rd))
	var AlarmD AlarmEvent
	jerr := json.Unmarshal(rd, &AlarmD)
	if jerr != nil {
		return
	}
	allAlarms := make([]*eventtype.Alarm, 0)
	//now := time.Now().Unix()
	tnow := time.Now()
	now := tnow.Unix()

	devInProvider := make(map[string]bool)
	fmt.Println("----------------read alarm--------for alarmD.OK-----")

	for _, v := range AlarmD.Ok {

		//fmt.Println("begin to --------", v.UID)
		//logger.SLog.Info("begin to --------", v.UID)
		uid := v.UID
		Mux.Lock()
		id, ok := boxmap[uid]
		Mux.Unlock()
<<<<<<< HEAD
		logger.SLog.Info("get from mediasoft uid:", uid, " id:", id, " eve:", v)
=======

>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
		if id == "" || !ok {
			fmt.Println("begin to ------give up id --==--", v.UID, id, ok)
			removeDev(uid)
			saveFile()

			continue
		}
		var pThing *cache.ThingInfo

		pThing, _ = cache.GetThing(id)

		// if pThing == nil {

		// }

		if pThing == nil {
			removeDev(uid)
			saveFile()
			if id == "" || !ok {
				fmt.Println("begin to ---pThing==nil-==--", v.UID, id, ok)
				logger.SLog.Info("remove dev --------", v.UID)
				continue
			}
			Mux.Lock()
			//id, ok := boxmap[uid]
			delete(boxmap, uid)
			delete(boxistrue, id)
			Mux.Unlock()
			continue
		}
		devInProvider[id] = true
		ip := pThing.Params["IP"]
		bid := pThing.Params["business_id"]
		mapIP[id] = ip

		var isoffline = false
		sort.Strings(v.Eve)
		//alarms, _ := rc.GetHashField(interfaceFHKey, id).Result()
		alarms, okFound := alarmLocalMap[id]
		nowAlarm := strings.Join(v.Eve, ",")
		if alarms != nowAlarm || (!okFound) { //没有找到或者告警不相同
			saveAlarm(v.Eve, id, ip)
			alarmLocalMap[id] = nowAlarm
		} else { //找到了并且告警相同,只同步一下设备状态
			var pAlarm *eventtype.Alarm
			isTellOffline := false
			for _, e := range v.Eve {

				if e == "5" {
					isTellOffline = true
					break
				}
			}
<<<<<<< HEAD
			if !isTellOffline { //在线
				pAlarm = createAlarm(id, "offline", 0, now, "", ip, "")
				pAlarm.AlarmName = "设备断网"
				pAlarm.Flag = "END"
				pAlarm.Checker = "onlineChecker2"
				notify.RawAlarm(pAlarm)

				pAlarm = createAlarm(id, "powerOffline", 0, now, "", ip, "")
				pAlarm.AlarmName = "市电掉电"
				pAlarm.Flag = "END"
				pAlarm.Checker = "onlineChecker2"
				notify.RawAlarm(pAlarm)
				//cache.SetThingState(id, "online", tnow)

			}
				continue

		}

		pSB := &SB{
			Id: id,
=======
			if !isTellOffline {
				pAlarm = createAlarm(id, "offline", 0, now, "", ip, "")
				pAlarm.Flag = "END"
				pAlarm.Checker = "onlineChecker2"
				notify.RawAlarm(pAlarm)
			}

			continue
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
		}

		pSB := &SB{
			Id: id,
		}
		devids = append(devids, id)
		logger.SLog.Info("alarm insert --------", v.UID, alarms, v.Eve)

		for _, e1 := range v.Eve {
			//fmt.Println("------------", e1, e1 == "5")
			if e1 == "5" { //此时出现断线告警，要追溯设备的断线原因
				isoffline = true
				pSB.Sbzt = 1
				pSB.Sbzx = 1
				break
			}
		}

		reason := ""

		//var isOnlineFromMap = isOnline(id, &mapOnline)
		//fmt.Println("begin check on-----end---", v.UID)

		fmt.Println("--------isoffline----", isoffline)

		if isoffline { //有5存在

			for _, e1 := range v.Eve {
				isBreak := false

				switch e1 {
				case "0", "1":
					reason = "市电断电"
					/*
						if e1 == "0" {
							reason = "市电断电"
						} else {
							reason = "市电断电或12V电源异常"
						}*/

					alarmPoff := createAlarm(id, "powerOffline", 0, now, reason, ip, bid)
					allAlarms = append(allAlarms, alarmPoff)
					logger.SLog.Info("220v alarm insert", id, " ", v.UID)
					isBreak = true
				case "2":
					reason = "市电断电"
					alarmPoff := createAlarm(id, "powerOffline", 0, now, reason, ip, bid)
					// alarmPoff := &eventtype.Alarm{
					// 	Flag: "BEGIN",
					// }
					// alarmPoff.TID = id
					// alarmPoff.Time = now
					// alarmPoff.Mindex = 0
					// alarmPoff.AlarmID = "powerOffline"
					// alarmPoff.Info.Params = make(map[string]interface{})
					// alarmPoff.Info.Params["reason"] = reason
					// alarmPoff.Info.Params["ip"] = ip
					// alarmPoff.Info.Params["business_id"] = pThing.Thing.BusinessID
					// alarmPoff.Checker = "devPrivider"
					allAlarms = append(allAlarms, alarmPoff)
					logger.SLog.Info("220v alarm insert", id, " ", v.UID)
					reason = "设备过流"
					isBreak = true
				case "3":
					reason = "设备漏电"
					alarmPoff := createAlarm(id, "leak", 0, now, reason, ip, bid)
					allAlarms = append(allAlarms, alarmPoff)
					logger.SLog.Info("设备漏电 insert", id, " ", v.UID)
					isBreak = true
				case "4":
					reason = "220 电压不稳"
					alarmPoff := createAlarm(id, "power unstable", 0, now, reason, ip, bid)
					allAlarms = append(allAlarms, alarmPoff)
					logger.SLog.Info("power unstable insert", id, " ", v.UID)
					isBreak = true

				}
				if isBreak {
					break
				}
			}

			alarm := &eventtype.Alarm{
				Flag: "BEGIN",
			}
			alarm.TID = id
			alarm.Time = now
			alarm.Mindex = 0
			alarm.AlarmID = "offline"
			alarm.AlarmName = "设备断网"
			pSB.Sbzx = 1
			pSB.Sbzt = 1
			alarm.Info.Params = make(map[string]interface{})

			if ip != "" {
				alarm.Info.Params["ip"] = pThing.Params["IP"]
				alarm.Info.Params["business_id"] = pThing.Thing.BusinessID
			}
			logger.SLog.Info("alarm insert --offline------", v.UID, " ", id, alarm.IsHide)
			alarm.Checker = "devPrivider"
			if len(reason) == 0 {
				reason = "网络故障"
				alarm.IsHide = false //该告警显示
<<<<<<< HEAD
				alarm.AlarmName = "设备断网"
=======
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
				pSB.Gmzt = 1

				if count == 1 { //开机启动不延时该告警
					allAlarms = append(allAlarms, alarm)
					//saveAlarmDict(v.Eve, id, ip)

				} else { //延时该告警
					pinfo, ok := alarmDelay[id]
					alarm.Info.Params["reason"] = reason
					if !ok { //没有这个告警
						alarmDelay[id] = &alarmInfo{
							pAlarm: alarm, //先不上报
<<<<<<< HEAD
							count:  5,     //坚持5*2秒后上报
=======
							count:  3,
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
							ip:     ip,
						}
					} else { //有这个告警
						pinfo.count--
						//alarmDelay[id] = info
					}
					for i, iid := range devids {
						if iid == id {
							devids = append(devids[:i], devids[i+1:]...)
							break
						}
					}
				}

				//allAlarms = append(allAlarms, alarm)
			} else {
				alarm.IsHide = true
				pSB.Sdzt = 1
				allAlarms = append(allAlarms, alarm)
				delete(alarmDelay, id)
			}

			//fmt.Println("--------reason----", reason)

		} else {
			logger.SLog.Info("online---------------------", v.UID, id)
			pSB.Sbzx = 0
		}
		//fmt.Println(" v.Eve-4--", v.UID, isoffline)
		hasCameraOffline := false
		if !isoffline { //不存在5
			for _, e := range v.Eve {

				ev, _ := strconv.ParseInt(e, 10, 64)
				if ev < 5 { //5以内的扔掉
					continue
				}

<<<<<<< HEAD
				ip := pThing.Params["IP"]
				var alarmID = AlarmList[e]
				bid := pThing.Thing.BusinessID
=======
			if e != "19" {
				alarm := &eventtype.Alarm{
					Flag: "BEGIN",
				}
				alarm.TID = id
				alarm.Time = now
				alarm.Mindex = 0
				alarm.AlarmID = alarmID
				alarm.Info.Params = make(map[string]interface{})
				alarm.Checker = "devPrivider"
				if e == "24" {
					if alarm.Info.Params == nil {
						alarm.Info.Params = make(map[string]interface{})
						alarm.Info.Params["reason"] = "箱门未授权"
					} else {
						alarm.Info.Params["reason"] = "箱门未授权"
					}
					//alarm.Reason = "箱门未授权"
				}
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0

				if e != "19" { //不是摄像机断线告警
					alarm := &eventtype.Alarm{
						Flag: "BEGIN",
					}
					alarm.TID = id
					alarm.Time = now
					alarm.Mindex = 0
					alarm.AlarmID = alarmID
					alarm.Info.Params = make(map[string]interface{})
					alarm.Checker = "devPrivider"
					if e == "24" {
						if alarm.Info.Params == nil {
							alarm.Info.Params = make(map[string]interface{})
							//alarm.Info.Params["reason"] = "箱门未授权"
						}
						alarm.Info.Params["reason"] = "箱门未授权"
						//alarm.Reason = "箱门未授权"
					}

					if ip != "" {
						alarm.Info.Params["ip"] = ip
						alarm.Info.Params["business_id"] = bid
					}
					allAlarms = append(allAlarms, alarm)
				} else { //摄像机告警
					hasCameraOffline = true
					devMsg, err := GetDevMsg(uid, alarmconn)
					if err == nil && len(devMsg.Dev) > 0 {
						if devMsg.Dev[0].Conect == "Offline" {
							//fmt.Println("error------------------offline", uid)
							break
						}

						camera := make(map[int64]bool)
						var i int64
						for i = 0; i < 8; i++ {
							camera[i] = true
						}
<<<<<<< HEAD
						for k, v := range devMsg.Dev[0].CamDrop {
							fmt.Println("CamDrop---------------", k, v)
							no := strings.Replace(k, "Cam", "", 1)
							index, errC := strconv.ParseInt(no, 10, 64)
							if errC != nil {
								logger.SLog.Error("k cannot changed to int", k)
								continue
							}
							delete(camera, index)
							alarm := &eventtype.Alarm{
								Flag: "BEGIN",
=======
						alarm.TID = id
						alarm.Time = now
						alarm.Mindex = index
						alarm.AlarmID = alarmID
						alarm.Checker = "devPrivider"
						if ip != "" {
							alarm.Info.Params = make(map[string]interface{})
							alarm.Info.Params["ip"] = ip
							alarm.Info.Params["business_id"] = bid
							//alarm.Info.Params["reason"] = "ping time out"

							ipcID := fmt.Sprintf("%s.%d", id, index)
							pIPC, _ := cache.GetThing(ipcID)
							if pIPC != nil {
								cache.SetThingState(ipcID, "offline", tnow)
								alarm.Info.Params["Camera"] = pIPC.Thing.SName
								alarm.Info.Params["Camera_BusinessID"] = pIPC.Thing.BusinessID
								cip := pIPC.GetThingParam("ip", "")
								alarm.Info.Params["CameraIP"] = cip
								alarm.Info.Params["B"] = v.B
								alarm.Info.Params["P"] = v.P
								if cip != "" {
									alarm.Info.Params["reason"] = pIPC.Thing.SName + "\r\n  (ip" + cip + ")"
								} else {
									alarm.Info.Params["reason"] = pIPC.Thing.SName + "\r\n  " + fmt.Sprintf("第%d路", index)
								}

							} else {
								fmt.Println("thing not found", ipcID)
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
							}
							alarm.TID = id
							alarm.Time = now
							alarm.Mindex = index
							alarm.AlarmID = alarmID
							alarm.Checker = "devPrivider"
							if ip != "" {
								alarm.Info.Params = make(map[string]interface{})
								alarm.Info.Params["ip"] = ip
								alarm.Info.Params["business_id"] = bid
								//alarm.Info.Params["reason"] = "ping time out"

								ipcID := fmt.Sprintf("%s.%d", id, index)
								pIPC, _ := cache.GetThing(ipcID)
								if pIPC != nil {
									cache.SetThingState(ipcID, "offline", tnow)
									alarm.Info.Params["Camera"] = pIPC.Thing.SName
									alarm.Info.Params["Camera_BusinessID"] = pIPC.Thing.BusinessID
									cip := pIPC.GetThingParam("ip", "")
									alarm.Info.Params["CameraIP"] = cip
									alarm.Info.Params["B"] = v.B
									alarm.Info.Params["P"] = v.P
									if cip != "" {
										alarm.Info.Params["reason"] = pIPC.Thing.SName + "\r\n  (ip" + cip + ")"
									} else {
										alarm.Info.Params["reason"] = pIPC.Thing.SName + "\r\n  " + fmt.Sprintf("第%d路", index)
									}

								} else {
									fmt.Println("thing not found", ipcID)
								}

							}
							//fmt.Println("report alarm ", alarm.TID, ip, uid, alarm.AlarmID, alarm.Mindex)
							allAlarms = append(allAlarms, alarm)
						}

						for k := range camera {
							ipcID := fmt.Sprintf("%s.%d", id, k)
							cache.SetThingState(ipcID, "online", tnow)
						}

					}
					//fmt.Println("-------alarm add ----", alarm)
				}

			}
			fmt.Println("-------------alarm end-------------")
		}

		if !hasCameraOffline {
			for k := 0; k < 8; k++ { //8个摄像头
				ipcID := fmt.Sprintf("%s.%d", id, k)
				if isoffline {
					cache.SetThingState(ipcID, "offline", tnow)
				} else {
					cache.SetThingState(ipcID, "online", tnow)
				}

			}
		}
<<<<<<< HEAD
		//烽火的接口
=======
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
		dbconn.DBConnection.Transaction(func(tx *gorm.DB) error {

			//var pSB = &SB{}
			var sb SB
			err := tx.Where("id = ?", id).First(&sb).Error

			sb.Id = id
			sb.Sbbh = ip
			sb.Sbzx = pSB.Sbzx
<<<<<<< HEAD

			sb.Kzsbmc = pThing.Thing.SName
			sb.Sbdz = pThing.Thing.SName     //pThing.GetStationName() 2021.2-23按烽火要求用详细地址
			sb.By1 = pThing.GetStationName() //sb.Sbdz //设备地址 2021.2-23按烽火要求用详细地址
=======
			sb.Zhgxsj = time.Now()
			sb.Kzsbmc = pThing.Thing.SName
			sb.Sbdz = pThing.GetStationName()
			sb.By1 = sb.Sbdz //设备地址
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
			sb.Sdzt = pSB.Sdzt
			sb.Gmzt = pSB.Gmzt
			if pSB.Sbzx == 1 || pSB.Sdzt == 1 { //设备断线或者市电故障
				sb.Sbzt = 1
				sb.Kzsbgdzt = 1
				sb.Dy = ""

			} else {
				sb.Kzsbgdzt = 0
				sb.Sbzt = 0
				if sb.Dy == "" {
					sb.Dy = "220"
				} else {
					fdy, errdf := strconv.ParseFloat(sb.Dy, 10)
					if errdf != nil {
						sb.Dy = "220"
					} else {
						if fdy > 250 || fdy < 100 {
							sb.Dy = "225.0"
						}
					}

				}

			}
			sb.Kzsbgdzt = pSB.Sdzt

			sb.Gmzt = pSB.Sbzx

			//sb.Kzsbgdzt = pSB.Sdzt

			sid := pThing.StationID
			sThing, _ := cache.GetThing(sid)
			if sThing != nil {
				sb.By2 = sThing.GetStationName()
			}
			sb.By3 = pThing.Thing.Lon
			sb.By4 = pThing.Thing.Lat
			//sb.Sbzt = 0

<<<<<<< HEAD
			sb.Zhgxsj = time.Now()
=======
>>>>>>> 6e0d288c7762dac5343d82b5b0a99402a794a7e0
			if err != nil {
				err = tx.Create(&sb).Error
			} else {
				err = tx.Save(&sb).Error
			}
			return err
		})

	}
	//fmt.Println("----------------read alarm--------for alarmD.OK--end---")
	//fmt.Println("---------------get alarms-----------ReportAllAlarms-------", allAlarms)

	alarmCount := len(allAlarms)

	Mux.Lock()
	//ids := make([]string, 0, len(boxmap))

	//i := 0
	var needSave = false
	for uid, id := range boxmap {
		//ids[i] = id
		//i++
		//var isOnlineFromMap = isOnline(id, &mapOnline)
		//ids = append(ids, id)
		told, _ := devInProvider[id]
		if !told {
			ip, _ := mapIP[id]
			if ip == "" {
				pThing, _ := cache.GetThing(id)
				if pThing == nil {
					continue
				}
				ip = pThing.Params["IP"]
				if ip == "" {
					continue
				}

				logger.SLog.Info("add------devf---------", uid, ip)

			}
			if ip != "" {
				AddDevf(uid, ip)
				needSave = true
			}

		}
	}
	Mux.Unlock()
	if needSave {
		saveFile()
	}
	logger.SLog.Info("alarm------search---------end", alarmCount)
	if alarmCount > 0 || len(devids) > 0 {
		notify.ReportAllAlarms(allAlarms, devids)
	}

	logger.SLog.Info("alarm---------------end")

	//fmt.Println("----------------read alarm--------for boxmap--begin---")

}

func createAlarm(id, aid string, aindex int, now int64, reason, ip, bid string) *eventtype.Alarm {
	alarmPoff := &eventtype.Alarm{
		Flag: "BEGIN",
	}
	alarmPoff.TID = id
	alarmPoff.Time = now
	alarmPoff.Mindex = 0
	alarmPoff.AlarmID = aid
	alarmPoff.Info.Params = make(map[string]interface{})
	alarmPoff.Info.Params["reason"] = reason
	alarmPoff.Info.Params["ip"] = ip
	alarmPoff.Info.Params["business_id"] = bid
	alarmPoff.Checker = "devPrivider"

	return alarmPoff
}
